package servlet.admin;

import entity.Operator;
import service.OperatorService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet( name = "AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String verify = request.getParameter("verify");
        OperatorService service=new OperatorService();

        List<Object> result = service.login(account, password);

        boolean accountIsOk = Boolean.parseBoolean(result.get(0).toString());
        boolean passwordIsOk = Boolean.parseBoolean(result.get(1).toString());
        boolean verifyIsok = true;

        String accountMessage = "";
        String passwordMessage = "";
        String VerifyMessage = "";
        if(!accountIsOk){
            accountMessage = "该帐号不存在";
        }
        if(!passwordIsOk){
            passwordMessage = "密码错误";
        }
        if(!verify.equalsIgnoreCase((String) request.getSession().getAttribute("text"))){
            VerifyMessage = "验证码输入错误！";
            verifyIsok = false;
        }

        //登录成功
        if(accountIsOk && passwordIsOk && verifyIsok){
            request.getSession().setAttribute("loginOperator", (Operator)result.get(2));
            request.getServletContext().getRequestDispatcher("/admin/index.jsp").forward(request, response);
        }
        //登录失败 ，还是跳转到登录界面
        else{
            request.setAttribute("account", account);
            request.setAttribute("accountMessage", accountMessage);
            request.setAttribute("password", password);
            request.setAttribute("passwordMessage", passwordMessage);
            request.setAttribute("VerifyMessage", VerifyMessage);
            request.getServletContext().getRequestDispatcher("/admin/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
